package com.demo.common.excel;


import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.demo.common.utils.JsonUtil;
import lombok.SneakyThrows;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;

/**
 * 导入数据处理listener
 */
public class ExcelSimpleListener extends AnalysisEventListener {
    /**
     * 当前场景class
     */
    private Class targetClass;
    /**
     * 读到的数据
     */
    private List list=new ArrayList<>();

    /**
     * excel列和实体字段的映射关系
     */
    private Map<Integer,FieldWrapper> fieldWrapperMap=new HashMap<>();

    public ExcelSimpleListener(List<FieldWrapper> fieldWrappers){
        for (int i = 0; i < fieldWrappers.size(); i++) {
            fieldWrapperMap.put(i,fieldWrappers.get(i));
        }
        targetClass=fieldWrappers.get(0).getField().getDeclaringClass();
    }

    @Override
    @SneakyThrows
    public void invoke(Object data, AnalysisContext context) {
        Map<String,Object> mapData=new HashMap<>();
        LinkedHashMap<String,Object> linkedHashMap= (LinkedHashMap) data;
        linkedHashMap.entrySet().forEach(it->{
            FieldWrapper fieldWrapper = fieldWrapperMap.get(it.getKey());
            Object value=it.getValue();
            if(fieldWrapper.getImportConverter()!=null){
                Function importConvert = ExcelUtils.getImportConvert(fieldWrapper.getImportConverter());
                if(importConvert!=null){
                    value=importConvert.apply(value);
                }
            }
            mapData.put(fieldWrapper.getField().getName(),value);
        });
        Object object = JsonUtil.json2Object(JsonUtil.object2Json(mapData), targetClass);
        list.add(object);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {

    }

    public List getData(){
        return list;
    }
}
